package space.panker916.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import space.panker916.utils.RedisKeyUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DataService {
    @Autowired
    private RedisTemplate redisTemplate;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

    // 将指定的 IP 计入 UV
    public void recordUV(String ip) {
        String date = simpleDateFormat.format(new Date());
        String uvKey = RedisKeyUtil.getUVKey(date);
        redisTemplate.opsForHyperLogLog().add(uvKey, ip);
    }

    // 统计区间内的 UV
    public long calculateUV(Date startDate, Date endDate) {
        if (startDate == null || endDate == null || startDate.after(endDate))
            throw new IllegalArgumentException("日期参数不合法");

        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while (calendar.getTime().before(endDate)) {
            String uvKey = RedisKeyUtil.getUVKey(simpleDateFormat.format(calendar.getTime()));
            keyList.add(uvKey);
            calendar.add(Calendar.DATE, 1);
        }

        // 返回合并日期内的数据
        return redisTemplate.opsForHyperLogLog().size(keyList.toArray());
    }

    // 将指定用户计入到 DAU 中
    public void recordDAU(int userId) {
        String dauKey = RedisKeyUtil.getDAUKey(simpleDateFormat.format(new Date()));
        redisTemplate.opsForValue().setBit(dauKey, userId, true);
    }

    // 统计指定日期范围内的 DAU 
    public long calculateDAU(Date startDate, Date endDate) {
        if (startDate == null || endDate == null || startDate.after(endDate))
            throw new IllegalArgumentException("日期参数不合法");

        List<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while (calendar.getTime().before(endDate)) {
            String dauKey = RedisKeyUtil.getDAUKey(simpleDateFormat.format(calendar.getTime()));
            keyList.add(dauKey.getBytes());
            calendar.add(Calendar.DATE, 1);
        }

        // 计算返回合并日期内的数据
        return (long) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                String dauKey = RedisKeyUtil.getDAUKey(simpleDateFormat.format(startDate), simpleDateFormat.format(endDate));
                connection.bitOp(RedisStringCommands.BitOperation.OR, dauKey.getBytes(), keyList.toArray(new byte[0][0]));
                return connection.bitCount(dauKey.getBytes());
            }
        });
    }
}
